import difflib

text1 = '''1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
'''.splitlines(keepends=True)

text2 = '''1. Beautiful is better than ugly.
3. Simple is better than complex.
4. Complicated is better than complex.
5. Flat is better than nested.
'''.splitlines(keepends=True)

#生成网页，比对文本异同
html_diff = difflib.HtmlDiff()
html_output = html_diff.make_file(text1, text2)

with open('diff_output.html', 'w') as f:
    f.write(html_output)


#文件比较
import difflib
filename1 = '/tmp/passwd'
filename2 = '/tmp/passwd1'

with open(filename1) as f1,open(filename2) as f2:
    content1 = f1.read().splitlines(keepends=True)
    content2 = f2.read().splitlines(keepends=True)


#生成网页，比对文本异同
d = difflib.HtmlDiff()
htmlcontent = d.make_file(content1,content2)
with open('passwdDiff.html','w') as f:
    f.write(htmlcontent)



#逐行比对
d = difflib.Differ()
print(''.join(list(d.compare(text1,text2))))




#1 匹配最大相似内容
import difflib
colors = ['red', 'blue', 'green', 'yellow', 'black', 'white']
wrong_color = "grren"
result = difflib.get_close_matches(wrong_color, colors)
print(result)

# ['green']



# 相比较 context_diff，ndiff 会以更加紧凑的格式展示每行文本的差异，
# 使用特定的标记符号来表示新增、删除和修改等操作。
# ‘-’    包含在第一个系列行中，但不包含第二个。
# ‘+’    包含在第二个系列行中，但不包含第一个。
# ’ ’    两个系列行一致。
# ‘?’    存在增量差异。
# ‘ ^ ’    存在差异字符。
#文件比对
# with open(ip + '_' + datetime.date.today().isoformat(), 'w+') as new_file, open(
#         ip + '_' + (datetime.date.today() - datetime.timedelta(days=1)).isoformat()) as old_file:
#     diff = list(difflib.ndiff(old_file.readlines(), new_file.readlines()))

import difflib

text1 = ['Hello', 'World', 'Python']
text2 = ['Hello', 'There', 'Python']


diff = difflib.ndiff(text1, text2)
for line in diff:
    print(line)

#   Hello
# - World
# + There
#   Python



